<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="区域">
							<uni-data-select
								v-model="searchModel.regionCode"
								placeholder="请选择区域"
								:localdata="setStore.allProvinceList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="预算名称">
							<uni-easyinput v-model="searchModel.name" placeholder="请输入预算名称" />
						</uni-forms-item>
						<uni-forms-item label="预算年月">
							<picker mode="date" fields="month" :value="searchModel.planMonth" @change="planMonthChange">
								<ty-picker
									placeholder="请选择预算年月"
									@clear="clearPicker"
									:value="searchModel.planMonth"></ty-picker>
							</picker>
						</uni-forms-item>
						<uni-forms-item label="状态">
							<uni-data-select
								v-model="searchModel.status"
								placeholder="请选择状态"
								:localdata="marketPlanStatusList"></uni-data-select>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
		</up-popup>
		<view class="content">
			<!--操作-->
			<view class="operate main-flex">
				<view class="operate-item" v-if="checkPermi(['zhouyz:marketPlan:add'])">
					<up-button
						class="operate-btn main-flex"
						size="mini"
						type="primary"
						@click="editFun()">
						<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">新增</view>
					</up-button>
				</view>
			</view>
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					@row-click="rowClick"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					:isOperateBtn="(row) => {
						return checkPermi(['zhouyz:marketPlan:edit', 'zhouyz:marketPlan:audit'])
					}"
					stripe
					border>
					<template v-slot:table1="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								名称：
								<text class="table-td-text">{{row.name}}</text>
							</view>
							<view class="table-td-row">
								年月：
								<text class="table-td-text">{{row.planMonth}}</text>
							</view>
						</view>
					</template>
					<template v-slot:table2="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								总金额：
								<text class="table-td-text">{{row.totalAmount}}</text>
							</view>
							<view class="table-td-row">
								剩余金额：
								<text class="table-td-text">{{row.totalBalance}}</text>
							</view>
						</view>
					</template>
					<template v-slot:table3="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								区域：
								<text class="table-td-text">{{`${arrText(setStore.allProvinceList, row.regionCode)}`}}</text>
							</view>
							<view class="table-td-row">
								状态：
								<uni-tag size="small" :text="arrText(marketPlanStatusList, row.status)" />
							</view>
						</view>
					</template>
					<template v-slot:operate="{ row }">
						<view class="table-td-operate table-cell table-td-row main-flex">
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:marketPlan:edit']) && row.status === 0">
								<up-button
									size="mini"
									type="primary"
									@click.stop="editFun(row.id)">
									<uni-icons class="table-operate-btn-icon" type="compose" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">修改</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="refreshFun(row.id)">
									<uni-icons class="table-operate-btn-icon" type="loop" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">刷新</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:marketPlan:edit']) && row.status === 0">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="primary"
									@click.stop="auditAddFun(row)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="20rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">提交审核</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:marketPlan:audit']) && row.status === 1">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="primary"
									@click.stop="auditFun(row.id)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="20rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">审核</view>
								</up-button>
							</view>
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
			</view>
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { marketPlan, marketPlanRefresh, marketPlanEdit, marketPlanAudit } from "@/api/erp_api/coupon"
import { isObjectEmptySimple, copyText, arrText } from '@/utils/ty.js'
import useUserStore from '@/store/modules/user';
import { marketPlanStatusList } from '@/utils/config.js'
import useSetStore from '@/store/modules/set';
import { timeFormat } from 'uview-plus'

	const userStore = useUserStore()
	const setStore = useSetStore()

	// 标题设置
	const title = ref('')
	onLoad((option) => {
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
		uni.$on('refreshList', () => {
			getList()
		})
	})
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		planMonth: timeFormat(new Date(), 'y-m'),
		status: '',
		name: '',
		regionCode: userStore.regionCode
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	
	// 选择年月
	const planMonthChange = (e) => {
		searchModel.value.planMonth = e.detail.value
	}
	const clearPicker = () => {
		searchModel.value.planMonth = ''
	}
	
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			planMonth: timeFormat(new Date(), 'y-m'),
			status: '',
			name: '',
			regionCode: userStore.regionCode
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '名称年月', key: 'table1' },
		{ title: '预算金额', key: 'table2' },
		{ title: '区域状态', key: 'table3' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.regionCode) {
			params.regionCode = searchModel.value.regionCode
		}
		if (searchModel.value.status || searchModel.value.status === 0) {
			params.status = searchModel.value.status
		}
		if (searchModel.value.name) {
			params.name = searchModel.value.name
		}
		if (searchModel.value.planMonth) {
			params.planMonth = searchModel.value.planMonth.replace(/-/g, '')
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		marketPlan(params).then(res => {
			tableList.value = res.rows || []
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 详情
	const rowClick = (row) => {
		uni.navigateTo({
			url: `/pages/coupon/marketPlanDetail?id=${row.id}`
		})
	}
	
	//刷新
	const refreshFun = (id) => {
		marketPlanRefresh({
			id
		}).then(res => {
			modal.showToast('刷新成功')
			getList()
		}).catch((err) => {
			modal.showToast(err)
		})
	}
	// 提交审核
	const auditAddFun = (row) => {
		uni.showModal({
			title: '提交审核',
			content: `是否确认提交审核?`,
			success: function (res) {
				if (res.confirm) {
					marketPlanEdit({
						...row,
						status: 1
					}).then(async (res1) => {
						modal.showToast(res1.msg)
						getList()
					})
				}
			}
		})
	}
	// 审核
	const auditFun = (id) => {
		uni.showModal({
			title: '审核',
			content: `是否确认审核通过?`,
			success: function (res) {
				if (res.confirm) {
					marketPlanAudit({
						id
					}).then(async (res) => {
						modal.showToast(res.msg)
						getList()
					})
				}
			}
		})
	}
	//编辑
	const editFun = (id) => {
		uni.navigateTo({
			url: id ? `/pages/coupon/marketPlanEdit?id=${id}` : `/pages/coupon/marketPlanEdit`
		})
	}
	
	// //删除
	// const deleteFun = (id) => {
	// 	uni.showModal({
	// 		title: '删除',
	// 		content: `是否确认删除优惠券编号为"${id}"的数据项?`,
	// 		success: function (res) {
	// 			if (res.confirm) {
	// 				deleteOne(id)
	// 			}
	// 		}
	// 	})
	// }
	// const deleteOne = (id) => {
		// couponDel({
		// 	id
		// }).then(res => {
		// 	modal.showToast('删除成功')
		// 	getList()
		// }).catch((err) => {
		// 	modal.showToast(err)
		// })
	// }
	
	watch(() => userStore.regionCode, (nval, oval) => {
		if (nval) {
			searchModel.value.regionCode = nval
			searchFirst()
		}
	})
	
	onMounted(() => {
		searchFirst()
	})
</script>

<style scoped>
.status1 {
	color: #19be6b;
}
.status2 {
	color: #fa3534;
}
</style>
